#include "nvmemclock.h"
#include <iostream>


NvMemClock::NvMemClock(QObject *parent)
{
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &NvMemClock::updateUtilization);
    timer->start(1000);

    // 初始化NVML
    nvmlReturn_t result = nvmlInit();
    if (result != NVML_SUCCESS) {
        std::cerr << "Failed to initialize NVML: " << nvmlErrorString(result) << std::endl;
    }
}

NvMemClock::~NvMemClock()
{
    if (timer != nullptr)
    {
        if (timer->isActive())
        {
            timer->stop();
        }
    }
    // 关闭NVML
    nvmlShutdown();
}


QString NvMemClock::getMemClock() const {
    unsigned int memoryClockMHz = 0;
    nvmlDevice_t device;
    nvmlReturn_t result = nvmlDeviceGetHandleByIndex(0, &device);
    if (result == NVML_SUCCESS) {
        result = nvmlDeviceGetClockInfo(device, NVML_CLOCK_MEM, &memoryClockMHz);
        if (result == NVML_SUCCESS) {
            return QString::number(memoryClockMHz) + " MHz";
        }
    }
    return QString("Unknown");
}

void NvMemClock::updateUtilization() {
    emit memClockChanged();
}

